import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'
import { getToken } from '@/utils/token'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/layout',
    // 路由的懒加载
    component: () => import('@/views/Layout'),
    children: [
      {
        path: 'home',
        component: () => import('@/views/Home/index.vue')
      },
      {
        path: 'user',
        component: () => import('@/views/User/index.vue')
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: () => import('@/views/Search')
  },
  {
    name: 'searchResult',
    path: '/search/:kw',
    component: () => import('@/views/SearchResult')
  },
  {
    path: '/articleDetail',
    component: () => import('@/views/ArticleDetail')
  },
  {
    path: '/edit_user',
    meta: { title: '编辑个人资料', requiresAuth: true },
    component: () => import('@/views/User/EditUser')
  },
  {
    path: '/chat',
    meta: { title: '编辑个人资料', requiresAuth: true },
    component: () => import('@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) { return originalPush.call(this, location, onResolve, onReject) }
  return originalPush.call(this, location).catch((err) => err)
}
// replace
VueRouter.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) { return originalReplace.call(this, location, onResolve, onReject) }
  return originalReplace.call(this, location).catch((err) => err)
}
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
// 判断to.matched
  if (to.matched.some(recorde => recorde.meta.requiresAuth)) {
    console.log(1)
    console.log(getToken())
    if (getToken()?.length > 0) {
      // 登录后就不能往登录页面去了
      if (to.path !== '/login') {
        console.log(2)
        next()
      } else {
        next({ path: '/layout/home' })
      }
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  } else {
    next()
  }
})

export default router
